<?php

namespace catchAdmin\newsDeclare\controller;

use catchAdmin\basics\request\AddDataCreateRequest;
use catchAdmin\externalGoods\model\Goods as externalGoodsModel;
use catchAdmin\newsDeclare\model\NewsDeclare;
use catchAdmin\externalGoods\service\GoodsService as externalGoodsService;
use catchAdmin\newsDeclare\model\NewsReview;
use catchAdmin\system\model\Attachments;
use catchAdmin\system\model\Config;
use catcher\base\CatchRequest as Request;
use think\Exception;
use think\facade\Db;
use think\Request as ThinkRequest;
use catcher\CatchAdmin;
use catcher\CatchAuth;
use catcher\CatchResponse;
use houniao\api\v1\Goods as GoodsApi;

class Institution extends CatchAdmin
{
    public function __construct(NewsDeclare $newsDeclareModel)
    {
        $this->newsDeclareModel = $newsDeclareModel;
    }

    //列表
    public function index(CatchAuth $auth, Request $request)
    {
        $user = $auth->user();
        return CatchResponse::paginate($this->newsDeclareModel->getList($user['tenant_id'],'all'));
    }

    //列表
    public function counts(CatchAuth $auth, Request $request)
    {
        $type = $request->param('type','institution.xw_post_num');
        if(!is_array($type)){
            $type = [$type];
        }
        $user = $auth->user();

        $max_counts = (new Config())
            ->where('key','in', $type)
            ->field('key,value')->select()->toArray();
        $_key = array_column($max_counts,'key');
        $_value = [];
        //有设置过数量 就用自己的
        foreach ($type as $key => $value){
            $_arr = explode('.',$value);
            if(! empty($user['rec_num'][$_arr[0]][$_arr[1]])){
                $_value[] = $user['rec_num'][$_arr[0]][$_arr[1]];
            }else{
                $_value[] = array_column($max_counts,'value')[$key];
            }
        }

        //$_value =  !empty($user['rec_num'][$type]) ? [$user['rec_num']] : array_column($max_counts,'value');
        $max_counts = array_combine($_key,$_value);

        $result = [
            'max_counts'=>$max_counts
        ];

        return CatchResponse::success($result);
    }

    public function create(CatchAuth $auth,Request $request)
    {
        $params = $request->post();
        $user = $auth->user();
        $params['tenant_id'] = $user['tenant_id'];
        $params['news_no'] = date('ymdHis') . mt_rand(1000,9999);

//        if(array_key_exists('back_attachments',$params) && !empty($params['back_attachments'])){
//            $params['is_declare'] = 1;
//        }
        unset($params['created_at']);
//        unset($params['author_name']);

        $id =  $this->newsDeclareModel->storeBy($params);
        $result = $this->newsDeclareModel->findBy($id);
        return CatchResponse::success($result,'新建成功');
    }

    public function declare(CatchAuth $auth,Request $request){
        $type = $request->post('type');
        $type_1 = $request->post('type_1');
        $user = $auth->user();

        $declare_info = $user['declare_info'];
        if(empty($declare_info)){
            $declare_info = [];
        }
        if($type  == 'xw'){
            $declare_info['xw_sb'] = 1;
            $_type_name ='新闻奖';
        }elseif(substr($type,0,2)  === 'cb'){
            $declare_info[$type . "_sb"] = 1;
            $_type_name ='传播奖';
        }
        $user->declare_info = $declare_info;

        Db::startTrans();
        try {
            $user->save();

            $where = ['type'=>$_type_name,'creator_id'=>$user['id']];
            if($type_1){
                $where['type_1'] = $type_1;
            }

            $this->newsDeclareModel::update([
                'is_declare'=>1
            ],$where);

            Db::commit();
        }catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('申报失败');
        }

        return CatchResponse::success();
    }

    public function detail($id,CatchAuth $auth, Request $request)
    {
        $user = $auth->user();
        $data = $this->newsDeclareModel->findBy($id);

        if(empty($data)) return CatchResponse::fail('参数错误');

        $data = $data->toArray();

        $data['attachments'] = !empty($data['attachments']) ? $data['attachments'] : [];
        $data['back_attachments'] = !empty($data['back_attachments']) ? $data['back_attachments'] : [];
        $data['attachments_cxxg'] = !empty($data['attachments_cxxg']) ? $data['attachments_cxxg'] : [];
//        $data['is_rec'] = $this->newsReviewModel->where([
//            'article_id'=>$id,
//            'judge_id'=>$user['id']
//        ])->value('id');

        foreach ($data['attachments_cxxg'] as &$value){
            $_d =  (new Attachments())->where('url',$value['file_fullurl'])->find()->toArray();
            $value['mime_type'] =$_d['mime_type'];
            $value['file_ext'] =$_d['file_ext'];
            $value['file_size'] =$_d['file_size'];
        }

        foreach ($data['attachments'] as &$value){
            $_d =  (new Attachments())->where('url',$value['file_fullurl'])->find()->toArray();
            $value['mime_type'] =$_d['mime_type'];
            $value['file_ext'] =$_d['file_ext'];
            $value['file_size'] =$_d['file_size'];
        }

        foreach ($data['back_attachments'] as &$value){
            $_d =  (new Attachments())->where('url',$value['file_fullurl'])->find()->toArray();
            $value['mime_type'] =$_d['mime_type'];
            $value['file_ext'] =$_d['file_ext'];
            $value['file_size'] =$_d['file_size'];
        }

        $data['recommendList'] = (new NewsReview())
            ->field('nr.created_at,u.username')
            ->alias('nr')
            ->leftJoin('users u','u.id = nr.judge_id')
            ->where('article_id',$data['id'])
            ->select()->toArray();

        return CatchResponse::success($data);
    }

    public function update($id,CatchAuth $auth,Request $request)
    {
        $params = $request->post();
        unset($params['news_no'],$params['created_at']);
        $user = $auth->user();

//        if(array_key_exists('back_attachments',$params) && !empty($params['back_attachments'])){
//            $params['is_declare'] = 1;
//        }

        $params['tenant_id'] = $user['tenant_id'];
//        unset($params['author_name']);

        return CatchResponse::success($this->newsDeclareModel->updateBy($id,$params),'修改成功');
    }

    public function delete($id,CatchAuth $auth,Request $request){

        return CatchResponse::success($this->newsDeclareModel->deleteBy($id));
    }

    public function saveInstitutionReporter(CatchAuth $auth,Request $request){
        $data = $request->post();
        $user = $auth->user();

        return CatchResponse::success($user->save($data));
    }
}